// 通用拖动逻辑，适用于 Vue3 组件
import { ref, onMounted, onBeforeUnmount } from 'vue'

export default function useDraggable(targetRef, options = {}) {
  const dragging = ref(false)
  const position = ref({ x: options.x || 100, y: options.y || 100 })
  let start = { x: 0, y: 0 }

  function onMouseDown(e) {
    dragging.value = true
    start = {
      x: e.clientX - position.value.x,
      y: e.clientY - position.value.y
    }
    document.addEventListener('mousemove', onMouseMove)
    document.addEventListener('mouseup', onMouseUp)
  }

  function onMouseMove(e) {
    if (!dragging.value) return
    position.value = {
      x: e.clientX - start.x,
      y: e.clientY - start.y
    }
  }

  function onMouseUp() {
    dragging.value = false
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)
  }

  onMounted(() => {
    if (targetRef.value) {
      targetRef.value.addEventListener('mousedown', onMouseDown)
    }
  })

  onBeforeUnmount(() => {
    if (targetRef.value) {
      targetRef.value.removeEventListener('mousedown', onMouseDown)
    }
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)
  })

  return {
    position,
    dragging,
    onMouseDown // 可选暴露
  }
} 